package com.silence.gmall.handler;

import cn.idev.excel.annotation.ExcelProperty;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.groups.Default;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @Author bing.wu
 * @Email 792245022@qq.com
 * @Date 2025-06-11 14:50
 * @Description Excel 校验信息处理器
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ExcelValidateHandler {

    /**
     * 校验器
     */
    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 校验实体类
     *
     * @param obj 实体类
     * @param <T> 实体类类型
     * @return 校验结果
     * @throws NoSuchFieldException 异常
     */
    public static <T> List<Map<String, Object>> validateEntity(T obj) throws NoSuchFieldException {
        List<Map<String, Object>> list = new ArrayList<>();
        Set<ConstraintViolation<T>> set = VALIDATOR.validate(obj, Default.class);
        if (CollectionUtils.isNotEmpty(set)) {
            for (ConstraintViolation<T> tConstraintViolation : set) {
                Field declaredField = obj.getClass().getDeclaredField(tConstraintViolation.getPropertyPath().toString());
                ExcelProperty annotation = declaredField.getAnnotation(ExcelProperty.class);
                Map<String, Object> map = HashMap.newHashMap(4);
                assert annotation != null;
                map.put("column", annotation.index() + 1);
                map.put("message", annotation.value()[0] + tConstraintViolation.getMessage());
                list.add(map);
            }
        }
        return list;
    }
}
